package com.credithc.customers.api.service.impl;

import com.credithc.baseserv.core.utils.UUIDUtils;
import com.credithc.customers.api.service.ICustomerCreditService;
import com.credithc.customers.api.service.ICustomerUnifyService;
import com.credithc.customers.base.codes.CustomerCodes;
import com.credithc.customers.base.configure.PropertiesConfig;
import com.credithc.customers.base.constants.CustomerConstants;
import com.credithc.customers.base.exception.CustomerException;
import com.credithc.customers.base.factory.DictionaryFactory;
import com.credithc.customers.base.po.CustomerExtendCreditPo;
import com.credithc.customers.base.ro.BaseRequest;
import com.credithc.customers.base.ro.CustomerUnifyRegisterRo;
import com.credithc.customers.base.ro.UnifyCreditRo;
import com.credithc.customers.base.service.ICommonService;
import com.credithc.customers.base.utils.ClassUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
@Slf4j
public class CustomerCreditServiceImpl implements ICustomerCreditService {
    @Autowired
    private ICommonService commonService;
    @Autowired
    private PropertiesConfig propertiesConfig;
    @Autowired
    private ICustomerUnifyService customerUnifyService;

    @Override
    public String getCredit(UnifyCreditRo ro) {
        log.info("【百朗查询是否授信】接口开始>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>入参：{}",ro);
        String backUrl;
        try {
            UnifyCreditRo.checkBaseParam(ro);
            String requestNo = ro.getRequestNo();
            String phone = ro.getPhone();
            String channelNo = ro.getChannel();
            String subSystemSign = ro.getSubSystemSign();
            String systemSign = ro.getSystemSign();
            String timeStamp = ro.getTimestamp();
            String verifyCode = ro.getVerifyCode();
            String ext1 = ro.getExt1();
            String ext2 = ro.getExt2();
            String ext3 = ro.getExt3();

            String redirectUrl;
            //h5接口验签 UNIFY_CHECK_RULE为code验签,否则不校验
            Map<String, String> checkRuleDictMap = DictionaryFactory.Dict.UNIFY_CHECK_RULE.getDictMap();
            String checkRule = checkRuleDictMap.get(subSystemSign);
            if (StringUtils.isNotBlank(checkRule) && (CustomerConstants.UNIFY_CHECK_ALL.equalsIgnoreCase(checkRule) || CustomerConstants.UNIFY_CHECK_CODE.equalsIgnoreCase(checkRule))) {
                commonService.verifyH5(systemSign, subSystemSign, timeStamp, verifyCode);
            }
            //查询CustomerExtendCreditPo信息是否存在
            CustomerExtendCreditPo creditPo = commonService.getCreditInfo(phone, channelNo, subSystemSign);
            //如果未授信，跳转到授信页面;如果已授信成功，跳转到ocr认证页面
            if (creditPo == null) {
                backUrl = propertiesConfig.getXhqbJumpUrl();
                redirectUrl = backUrl + "?phone=" + phone + "&channel=" + channelNo + "&subSystemSign=" + subSystemSign + "&systemSign=" + systemSign + "&timeStamp=" + timeStamp + "&verifyCode=" + verifyCode + "&ext1=" + ext1 + "&ext2=" + ext2 + "&ext3=" + ext3 + "&requestNo=" + requestNo + "&money=" + ro.getMoney();
            } else {
                Map<String, String> xhqbMap = commonService.getOnlineToken(systemSign, ext3, channelNo, ext1, requestNo, phone, creditPo.getPreCustomerNo(), ext2,ro.getMoney());
                backUrl = xhqbMap.get("h5Url");
                String code = xhqbMap.get("code");
                String error = xhqbMap.get("error");
                if (StringUtils.isBlank(backUrl)) {
                    throw new CustomerException(CustomerCodes.PARAM_VALIDATE_ERROR, "回调小恒钱包获取token异常:" + error);
                }
                if (xhqbMap.containsKey("token")) {
                    String token = xhqbMap.get("token");
                    redirectUrl = xhqbMap.get("h5Url") + "?code=" + code + "&error=" + error + "&token=" + token + "&merchantNo=" + channelNo + "&courseId=" + ext1 + "&requestNo=" + requestNo + "&money=" + ro.getMoney();
                } else {
                    redirectUrl = xhqbMap.get("h5Url") + "?code=" + code + "&error=" + error + "&merchantNo=" + channelNo + "&courseId=" + ext1 + "&requestNo=" + requestNo + "&money=" + ro.getMoney();
                }
            }
            log.info("redirectUrl:" + redirectUrl);
            return redirectUrl;
        } catch (CustomerException e) {
            log.error("【百朗查询是否授信】接口异常:" + ClassUtils.getClassName() + "--" + ClassUtils.getMethodName() + "--" + e.getMessage());
            String error = e.getMsg();
            backUrl = propertiesConfig.getXhqbErrorUrl();
            return backUrl + "?code=" + CustomerCodes.PARAM_VALIDATE_ERROR + "&error=" + error;
        }
    }

    @Override
    public String credit(UnifyCreditRo ro) {
        log.info("【百朗授信跳转】接口开始>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>入参：{}",ro);
        String redirectUrl = null;
        String backUrl;
        String code;
        String error;
        try {
            UnifyCreditRo.checkBaseParam(ro);
            String requestNo = ro.getRequestNo();
            String phone = ro.getPhone();
            String channelNo = ro.getChannel();
            String subSystemSign = ro.getSubSystemSign();
            String systemSign = ro.getSystemSign();
            String timeStamp = ro.getTimestamp();
            String verifyCode = ro.getVerifyCode();
            String ext1 = ro.getExt1();
            String ext2 = ro.getExt2();
            String ext3 = ro.getExt3();
            String money = ro.getMoney();
            String preCustomerNo;
            //h5接口验签 UNIFY_CHECK_RULE为code验签,否则不校验
            Map<String, String> checkRuleDictMap = DictionaryFactory.Dict.UNIFY_CHECK_RULE.getDictMap();
            String checkRule = checkRuleDictMap.get(subSystemSign);
            if (StringUtils.isNotBlank(checkRule) && (CustomerConstants.UNIFY_CHECK_ALL.equalsIgnoreCase(checkRule) || CustomerConstants.UNIFY_CHECK_CODE.equalsIgnoreCase(checkRule))) {
                commonService.verifyH5(systemSign, subSystemSign, timeStamp, verifyCode);
            }
            CustomerExtendCreditPo creditPo = commonService.getCreditInfo(phone, channelNo, subSystemSign);
            //授信成功，返回前端相应结果
            if (creditPo == null) {
                String yztRequestNo = "CREDIT" + requestNo+"_" + UUIDUtils.getUUID();
                BaseRequest<CustomerUnifyRegisterRo> preRequest = new BaseRequest<>();
                CustomerUnifyRegisterRo registerRo = new CustomerUnifyRegisterRo();
                registerRo.setRequestNo(yztRequestNo);
                registerRo.setPhone(phone);
                preRequest.setSystemSign(systemSign);
                preRequest.setSubSystemSign(subSystemSign);
                preRequest.setBody(registerRo);
                // 内部调取注册接口
                Map<String, Object> preMap = customerUnifyService.createPre(preRequest);
                preCustomerNo = preMap.get("preCustomerNo").toString();
            } else {
                //已授信跳转,一般不会走到此流程
                preCustomerNo = creditPo.getPreCustomerNo();
            }
            //从小恒钱包获取token及跳转地址
            Map<String, String> xhqbMap = commonService.getOnlineToken(systemSign, ext3, channelNo, ext1, requestNo, phone, preCustomerNo, ext2,money);
            backUrl = xhqbMap.get("h5Url");
            code = xhqbMap.get("code");
            error = xhqbMap.get("error");
            if (StringUtils.isBlank(backUrl)) {
                throw new CustomerException(CustomerCodes.PARAM_VALIDATE_ERROR, "回调小恒钱包获取token异常:" + error);
            }
            if (xhqbMap.containsKey("token")) {
                //获取token成功，则渠道授信表新增授信跳转记录
                if (creditPo == null) {
                    commonService.insertCustExtendCredit(systemSign, subSystemSign, channelNo, preCustomerNo, ext1, ext2, ext3, phone);
                }
                String token = xhqbMap.get("token");
                redirectUrl = backUrl + "?code=" + code + "&error=" + error + "&token=" + token + "&merchantNo=" + channelNo + "&courseId=" + ext1 + "&requestNo=" + requestNo + "&money=" + money;
            } else {
                redirectUrl = backUrl + "?code=" + code + "&error=" + error + "&merchantNo=" + channelNo + "&courseId=" + ext1 + "&requestNo=" + requestNo + "&money=" + money;
            }
        } catch (CustomerException e) {
            error = e.getMsg();
            backUrl = propertiesConfig.getXhqbErrorUrl();
            redirectUrl = backUrl + "?code=" + CustomerCodes.PARAM_VALIDATE_ERROR + "&error=" + error;
        } finally {
            log.info("redirectUrl:" + redirectUrl);
            return redirectUrl;
        }
    }

}
